package renguanyu.app.auth4fx.service.permission;

import renguanyu.app.auth4fx.dao.permission.PermissionDao;
import renguanyu.app.auth4fx.model.Page;
import renguanyu.app.auth4fx.model.permission.PermissionDto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PermissionService {

    public static Page getPermissionPage(PermissionDto permissionDto){
        Page page = new Page();
        page.setPageCount(countPermissionPages(permissionDto));
        page.setPageData(listPermissionsByPage(permissionDto));
        return page;
    }

    public static Integer countPermissionPages(PermissionDto permissionDto) {
        String name = permissionDto.getName();
        Integer pageSize = permissionDto.getPageSize();
        Integer total = PermissionDao.getPermissionTotal(name);
        Integer totalPage = (total + pageSize - 1) / pageSize;
        return totalPage;
    }

    public static List<Map<String, Object>> listPermissionsByPage(PermissionDto permissionDto) {
        Integer pageSize = permissionDto.getPageSize();
        Integer currentPageIndex = permissionDto.getCurrentPageIndex();
        String name = permissionDto.getName();
        Integer limit = pageSize;
        Integer offset = currentPageIndex * pageSize;
        return PermissionDao.getPagedPermissions(limit, offset, name);
    }

    public static Integer savePermission(PermissionDto permissionDto){
        String name = permissionDto.getName();
        return PermissionDao.savePermission(name);
    }

    public static Integer updatePermission(PermissionDto permissionDto){
        String id = permissionDto.getId();
        String name = permissionDto.getName();
        return PermissionDao.updatePermission(name,id);
    }

    public static Integer deletePermission(PermissionDto permissionDto){
        List<String> ids = permissionDto.getIds();
        String inSql = ids.stream().map(id -> "?").collect(Collectors.joining(","));
        return PermissionDao.deletePermission(ids,inSql);
    }

}
